package com.example.musicserver.controller;

import com.example.musicserver.common.Constant;
import com.example.musicserver.common.Response;
import com.example.musicserver.mapper.UserMapper;
import com.example.musicserver.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RequestMapping("/user")
@RestController
public class UserController {
    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;
    @Autowired
    private UserMapper userMapper;

    /**
     * 注册
     * @param user
     * @return
     */
    @RequestMapping("/reg")
    public Response<User> reg(User user){
        // 1. 校验参数
        if(user == null || !StringUtils.hasLength(user.getUsername())
        || !StringUtils.hasLength(user.getPassword())){
            return new Response<User>(-1,"非法参数！",null);
        }

        User userInSQL = userMapper.selectUsername(user);
        if (userInSQL != null){
            return new Response<User>(-1,"已存在相同用户名，请更改！",null);
        }

        // 2. 使用 BCrypt 加密
        user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));

        // 3. 将用户信息添加进数据库里
        int ret = userMapper.add(user);
        // 从数据库里取出用户的id
        System.out.println(user.getId());

        // 4. 将数据返回给前端
        return new Response<>(1,"注册成功！",user);
    }

    @RequestMapping("/login")
    public Response<User> login(User user, HttpServletRequest request){
        // 1. 校验参数
        if(user == null || !StringUtils.hasLength(user.getUsername())
                || !StringUtils.hasLength(user.getPassword())){
            return new Response<User>(-1,"非法参数！",null);
        }

        User userInSQL = userMapper.selectUsername(user);
        if(userInSQL == null){
            System.out.println("登陆失败！");
            return new Response<User>(-1,"用户名或密码错误！",user);
        }else{
            boolean flg = bCryptPasswordEncoder.matches(user.getPassword(), userInSQL.getPassword());
            if(!flg){
                return new Response<User>(-1,"用户名或密码错误！",user);
            }
            request.getSession().setAttribute(Constant.USER_SESSION_KEY,userInSQL);
            return new Response<User>(1,"登陆成功！",userInSQL);
        }

    }
}
